package asher.dotatbg.http.connector;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.Date;

import org.apache.log4j.Logger;

import asher.dotatbg.http.bean.HttpHeader;
import asher.dotatbg.http.parser.HttpHeaderParser;
import asher.dotatbg.http.processor.HttpProcessor;
import asher.dotatbg.logfactory.LogFactory;

/**
 * 总连接器，负责将服务器监听到的socket接收过来，并完成如下工作
 * 1.读取request信息
 * 2.解析http协议
 * 3.根据上一步解析的结果，执行不同的操作
 * @author AsherYuan
 */
public class CoreConnector {
	
	private static Logger logger = LogFactory.getRootLogger();
	private Socket socket = null;
	private InputStream input = null;
	
	/**
	 * 构造函数，主要初始化socket和输入流，并自动调用connect()方法
	 * @param socket 由服务器监听接受到的socket
	 */
	public CoreConnector(Socket socket) {
		this.socket = socket;
		try {
			this.input = this.socket.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.connect();
	}
	
	/**
	 * 连接方法：完成对socket通信中的request信息的解析
	 * 根据解析出来的信息，调用不同的处理器（如http处理器和游戏处理器）
	 */
	public void connect() {
		StringBuffer request = new StringBuffer(2048);
		int i;
		byte[] buffer= new byte[2048];
		
		try {
			i = input.read(buffer);
		} catch(IOException e) {
			e.printStackTrace();
			i = -1;
		}
		
		for(int j=0;j<i;j++) {
			request.append((char) buffer[j]);
		}
		
		HttpHeader httpHeader = HttpHeaderParser.parserHeader(request.toString());
		logger.info("连接器解析到的uri为： " + httpHeader.getHttpRequestUri() + "........." + new Date().toString());
		
		HttpProcessor processor = new HttpProcessor(httpHeader, socket);
		processor.process();
	}
}
